//
//  FeedListViewController.m
//  collection
//
//  Created by 张靖 on 5/22/12.
//  Copyright (c) 2012 Tsinghua University. All rights reserved.
//

#import "FeedListViewController.h"
#import "FeedDetailController.h"
#import "UIPullingheaderTableView.h"
#import "CollectionDataManager.h"
#import "FeedCell.h"
#import "LoadingMoreFooterView.h"
#import "MBProgressHUDHelper.h"
#import "AppDelegate.h"

@interface FeedListViewController ()

@property (retain, nonatomic) IBOutlet UIPullingheaderTableView *feedTableView;
@property (retain, nonatomic) IBOutlet UILabel *navTitle;
@property (nonatomic, retain)   NSArray* feedList;
@property (nonatomic, retain)   LoadingMoreFooterView* loadingmoreView;
@property (nonatomic) BOOL loadingmore;

- (IBAction)onClickBackBarItem:(id)sender;
- (void)updateFeedList;

@end

@implementation FeedListViewController

@synthesize tag = _tag;
@synthesize feedTableView = _feedTableView;
@synthesize navTitle = _navTitle;
@synthesize feedList = _feedList;
@synthesize loadingmoreView = _loadingmoreView;
@synthesize loadingmore = _loadingmore;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc {
    
    self.feedList = nil;
    self.loadingmoreView = nil;
    
    [_feedTableView release];
    [_navTitle release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.feedTableView.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"all_bg"]];
    
    self.navTitle.text = self.tag;
    
    LoadingMoreFooterView* loadFooterView = [[LoadingMoreFooterView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44.f)];
    self.loadingmore = NO;
    self.loadingmoreView = loadFooterView;
    [loadFooterView release];
    [self.feedTableView.tableFooterView addSubview:self.loadingmoreView];
}

- (void)viewDidUnload
{
    [self setFeedTableView:nil];
    [self setNavTitle:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UITableViewDataSource]

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.feedList != nil) {
        return 1;
    }
    else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.feedList.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString* latestInfoCellID = @"LatestInfoCell";
    FeedCell* cell = (FeedCell*)[tableView dequeueReusableCellWithIdentifier:latestInfoCellID];
    if (cell == nil) {
        cell = [[[FeedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:latestInfoCellID] autorelease];
    }
    
    // Customise the cell
    Feed* feed = [self.feedList objectAtIndex:indexPath.row];
    [cell updateCell:feed delegate:nil];
    
    return cell;
}

#pragma mark - [UITableViewDelegate]

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

    return cell.frame.size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // To do
    FeedDetailController* feedDetailController = [[FeedDetailController alloc] initWithNibName:@"FeedDetailController" bundle:nil];
    feedDetailController.feed = [self.feedList objectAtIndex:indexPath.row];
    
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.rootNavigationController pushViewController:feedDetailController animated:YES];
    [feedDetailController release];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - [UIScrollViewDelegate]

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    
    if (bottomEdge >= scrollView.contentSize.height )
    {
        if (self.loadingmore) return;
        
        NSLog(@"load more");
        self.loadingmore = YES;
        self.loadingmoreView.showActivityIndicator = YES;
        
        [self performSelector:@selector(onClickGetMore:) withObject:self afterDelay:1.0f]; //make a delay to show loading process for a while
    }
}

#pragma mark - [Private methods]

- (void)onInvokePullingRefresh:(UIPullingheaderTableView*)tableView {
    
    [self refresh];
}

- (void)delayFinishedRefreshLoading {
    
    [self.feedTableView reloadData];
    [self.feedTableView finishedRefreshLoading:0.0f];
    
    MBProgressHUD* indicatorView = [MBProgressHUDHelper popUpMBProcessHUD:self.view delegate:nil];
    [MBProgressHUDHelper changeToMBSuccessMode:indicatorView customMsg:@"更新完毕" afterDelay:1.0f];
}

- (void)refresh {
    
    NSLog(@"Refresh");
    [NSTimer scheduledTimerWithTimeInterval:2.0f
                                     target:self 
                                   selector:@selector(delayFinishedRefreshLoading)
                                   userInfo:nil
                                    repeats:NO];
}

- (IBAction)onClickBackBarItem:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    //    self.navigationController.navigationBarHidden = YES;
}

- (void)setTag:(NSString *)tag {
    [_tag release];
    _tag = [tag copy];
    
    [self updateFeedList];
    [self.feedTableView reloadData];
}

- (void)updateFeedList {
    
    CollectionDataManager* dataManager = [CollectionDataManager sharedInstance];
    self.feedList = [dataManager feedListWithTag:self.tag];
}

- (void)onClickGetMore:(id)sender {
    
    NSLog(@"Click get more");
    
    NSArray* newFeedList = [NSArray array];
    
    
    if (newFeedList.count > 0) {
        [self.feedTableView reloadData];
    }
    else {
        NSLog(@"No more feeds");
    }
    
    self.loadingmore = NO;
    self.loadingmoreView.showActivityIndicator = NO;
}

@end
